<template>
  <div class="paper-edit-container">
    <h1>修改论文</h1>
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="150px"
        label-position="top"
        class="paper-form"
    >
      <!-- 论文基本信息 -->
      <el-card shadow="hover" class="form-section">
        <template #header>
          <div class="card-header">
            <span>论文基本信息</span>
            <el-tag :type="getStatusType(form.status)" size="small" effect="light">
              {{ getStatusText(form.status) }}
            </el-tag>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="论文标题" prop="paperTitle">
              <el-input
                  v-model="form.paperTitle"
                  placeholder="请输入论文标题"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="期刊名称" prop="journal">
              <el-input
                  v-model="form.journal"
                  placeholder="请输入期刊名称"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="卷号" prop="volume">
              <el-input
                  v-model="form.volume"
                  placeholder="卷号"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="期号" prop="issue">
              <el-input
                  v-model="form.issue"
                  placeholder="期号"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页码范围" prop="pageRange">
              <el-input
                  v-model="form.pageRange"
                  placeholder="格式: 起始页-结束页"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="检索级别" prop="indexLevel">
              <el-select
                  v-model="form.indexLevel"
                  placeholder="请选择检索级别"
                  clearable
                  :disabled="form.status === 2"
              >
                <el-option label="SCI" value="SCI" />
                <el-option label="SSCI" value="SSCI" />
                <el-option label="EI" value="EI" />
                <el-option label="核心期刊" value="核心" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="影响因子" prop="impactFactor">
              <el-input-number
                  v-model="form.impactFactor"
                  :min="0"
                  :step="0.1"
                  :precision="2"
                  controls-position="right"
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发表日期" prop="publishDate">
              <el-date-picker
                  v-model="form.publishDate"
                  type="date"
                  placeholder="选择发表日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :disabled-date="disabledDate"
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="论文链接/DOI" prop="paperLink">
          <el-input
              v-model="form.paperLink"
              placeholder="请输入论文链接或DOI"
              clearable
              :disabled="form.status === 2"
          />
        </el-form-item>
      </el-card>

      <!-- 作者信息 -->
      <el-card shadow="hover" class="form-section">
        <template #header>
          <div class="card-header">
            <span>作者信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="第一作者" prop="firstAuthor">
              <el-input
                  v-model="form.firstAuthor"
                  placeholder="第一作者姓名"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯作者" prop="correspondingAuthor">
              <el-input
                  v-model="form.correspondingAuthor"
                  placeholder="通讯作者姓名"
                  clearable
                  :disabled="form.status === 2"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="作者名单" prop="authors">
          <el-button
              type="primary"
              @click="addAuthor"
              icon="el-icon-plus"
              size="small"
              :disabled="form.status === 2"
          >
            添加作者
          </el-button>

          <transition-group name="author-list" tag="div">
            <div
                v-for="(author, index) in form.authors"
                :key="index"
                class="author-item"
            >
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-input
                      v-model="author.name"
                      placeholder="作者姓名"
                      size="small"
                      :disabled="form.status === 2"
                  />
                </el-col>
                <el-col :span="6">
                  <el-input
                      v-model="author.affiliation"
                      placeholder="所属单位"
                      size="small"
                      :disabled="form.status === 2"
                  />
                </el-col>
                <el-col :span="4">
                  <el-select
                      v-model="author.order"
                      placeholder="顺序"
                      size="small"
                      :disabled="form.status === 2"
                  >
                    <el-option
                        v-for="n in 10"
                        :key="n"
                        :label="n"
                        :value="n"
                    />
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="small"
                      circle
                      @click="removeAuthor(index)"
                      :disabled="form.status === 2"
                  />
                </el-col>
              </el-row>
            </div>
          </transition-group>
        </el-form-item>
      </el-card>

      <div class="form-actions">
        <el-button
            v-if="form.status !== 2"
            type="primary"
            @click="saveAsDraft"
            :loading="loading"
            icon="el-icon-edit"
            size="small"
        >
          保存草稿
        </el-button>
        <el-button
            v-if="form.status !== 2"
            type="success"
            @click="submitForReview"
            :loading="loading"
            icon="el-icon-check"
            size="small"
        >
          提交审核
        </el-button>
        <el-button
            @click="resetForm"
            :disabled="form.status === 2"
            icon="el-icon-refresh"
            size="small"
        >
          重置修改
        </el-button>
        <el-button
            @click="goBack"
            icon="el-icon-back"
            size="small"
        >
          返回
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { updatePaper, getPaperDetails } from '@/api/paper';
import { useAuthStore } from '@/stores/auth';

export default {
  setup() {
    const route = useRoute();
    const router = useRouter();
    const authStore = useAuthStore();
    const formRef = ref(null);

    const loading = ref(false);
    const paperId = ref(route.params.id);

    // 表单数据
    const form = reactive({
      paperTitle: '',
      journal: '',
      issue: '',
      volume: '',
      pageRange: '',
      indexLevel: '',
      authors: [],
      firstAuthor: '',
      correspondingAuthor: '',
      publishDate: '',
      impactFactor: 0,
      paperLink: '',
      status: 0,
      submitUserId: authStore.user?.userId
    });

    // 表单验证规则
    const rules = reactive({
      paperTitle: [
        { required: true, message: '论文标题不能为空', trigger: 'blur' },
        { max: 500, message: '论文标题长度不能超过500字符', trigger: 'blur' }
      ],
      journal: [
        { required: true, message: '期刊名称不能为空', trigger: 'blur' },
        { max: 200, message: '期刊名称长度不能超过200字符', trigger: 'blur' }
      ],
      firstAuthor: [
        { required: true, message: '第一作者不能为空', trigger: 'blur' },
        { max: 100, message: '第一作者名称长度不能超过100字符', trigger: 'blur' }
      ],
      publishDate: [
        { required: true, message: '发表日期不能为空', trigger: 'change' }
      ],
      authors: [
        {
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error('至少需要添加一位作者'));
              return;
            }

            const invalidAuthors = value.filter(author =>
                !author.name || !author.name.trim() || author.order === undefined
            );

            if (invalidAuthors.length > 0) {
              callback(new Error('所有作者必须填写姓名和顺序'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]
    });

    // 获取状态标签类型
    const getStatusType = (status) => {
      switch (status) {
        case 2: return 'success'; // 已审核
        case 1: return 'warning'; // 已提交
        case 0: return 'info';    // 草稿
        default: return '';
      }
    };

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '草稿';
        case 1: return '已提交';
        case 2: return '已审核';
        default: return '未知状态';
      }
    };

    // 禁用未来日期
    const disabledDate = (time) => {
      return time.getTime() > Date.now();
    };

    // 添加作者
    const addAuthor = () => {
      form.authors.push({
        name: '',
        affiliation: '',
        order: form.authors.length + 1
      });
    };

    // 删除作者
    const removeAuthor = (index) => {
      form.authors.splice(index, 1);
      // 重新排序
      form.authors.forEach((author, idx) => {
        author.order = idx + 1;
      });
    };

    // 加载论文数据
    const loadPaperData = async () => {
      try {
        loading.value = true;
        const response = await getPaperDetails(paperId.value);
        const paperData = response.data;

        // 处理authors数据，确保是数组
        let authorsData = [];
        try {
          if (paperData.authors) {
            if (typeof paperData.authors === 'string') {
              authorsData = JSON.parse(paperData.authors);
            } else if (Array.isArray(paperData.authors)) {
              authorsData = paperData.authors;
            }
          }

          if (!Array.isArray(authorsData)) {
            authorsData = [];
          }
        } catch (e) {
          console.error('解析authors数据失败:', e);
          authorsData = [];
        }

        // 填充表单数据
        Object.assign(form, {
          paperTitle: paperData.paperTitle || '',
          journal: paperData.journal || '',
          issue: paperData.issue || '',
          volume: paperData.volume || '',
          pageRange: paperData.pageRange || '',
          indexLevel: paperData.indexLevel || '',
          authors: authorsData,
          firstAuthor: paperData.firstAuthor || '',
          correspondingAuthor: paperData.correspondingAuthor || '',
          publishDate: paperData.publishDate || '',
          impactFactor: paperData.impactFactor || 0,
          paperLink: paperData.paperLink || '',
          status: paperData.status || 0
        });

        // 确保作者顺序正确
        form.authors.forEach((author, index) => {
          author.order = author.order || index + 1;
        });

      } catch (error) {
        console.error('获取论文详情失败:', error);
        ElMessage.error(error.message || '获取论文详情失败');
        router.push({ name: 'StudentPaperManagement' });
      } finally {
        loading.value = false;
      }
    };

    // 重置表单
    const resetForm = () => {
      ElMessageBox.confirm('确定要重置所有修改吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        loadPaperData();
        ElMessage.success('已重置修改');
      }).catch(() => {
        ElMessage.info('已取消重置');
      });
    };

    // 保存为草稿
    const saveAsDraft = async () => {
      try {
        await formRef.value.validate();
        loading.value = true;

        const formData = {
          ...form,
          status: 0, // 草稿状态
          authors: JSON.stringify(form.authors) // 将作者数组转为JSON字符串
        };

        const response = await updatePaper(paperId.value, formData);
        ElMessage.success(response.message || '草稿保存成功');
        router.push({ name: 'StudentPaperManagement' });

      } catch (error) {
        console.error('保存草稿失败:', error);
        ElMessage.error(error.response?.data?.message || error.message || '保存草稿失败');
      } finally {
        loading.value = false;
      }
    };

    // 提交审核
    const submitForReview = async () => {
      try {
        await formRef.value.validate();
        loading.value = true;

        const formData = {
          ...form,
          status: 1, // 提交审核状态
          authors: JSON.stringify(form.authors) // 将作者数组转为JSON字符串
        };

        const response = await updatePaper(paperId.value, formData);
        ElMessage.success(response.message || '论文提交成功');
        router.push({ name: 'StudentPaperManagement' });

      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error(error.response?.data?.message || error.message || '提交失败');
      } finally {
        loading.value = false;
      }
    };

    // 返回
    const goBack = () => {
      router.push({ name: 'StudentPaperManagement' });
    };

    onMounted(() => {
      loadPaperData();
    });

    return {
      formRef,
      form,
      rules,
      loading,
      getStatusType,
      getStatusText,
      disabledDate,
      addAuthor,
      removeAuthor,
      resetForm,
      saveAsDraft,
      submitForReview,
      goBack
    };
  }
};
</script>

<style scoped>
.paper-edit-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.paper-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-item {
  margin-top: 10px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.author-list-enter-active,
.author-list-leave-active {
  transition: all 0.3s ease;
}

.author-list-enter-from,
.author-list-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.el-form-item {
  margin-bottom: 22px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .paper-edit-container {
    padding: 10px;
  }

  .form-actions {
    flex-wrap: wrap;
  }

  .el-form-item {
    margin-bottom: 18px;
  }
}
</style>